<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Exception;

class TestController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'Test';
    }

    /**
     * 导出
     */
    public function export(Request $request)
    {
        set_time_limit(300); // 超时
        ini_set('memory_limit', '1024M'); // 内存溢出

        $param = $request->all();
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $where = [
            ['id', '<', '100001']
        ];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        $data = $model->where($where)->order('created_at', 'asc')->limit(1000)->get()->toArray(); // 查询1万条会出错
        /*$cellName = array(
            'A' => ['id', '序号'],
            'B' => ['admin_id', '管理员'],
            'C' => ['name', '名称'],
            'D' => ['info', '详情'],
            'E' => ['created_at', '创建时间'],
        );*/
        $cellName = array(
            ['id', '序号', 8],
            ['admin_id', '管理员', 10],
            ['name', '名称', 16],
            ['info', '详情', 20],
            ['created_at', '创建时间', 18],
        );

        $filePath = config('path.upload_path') . 'csv/test/' . date('Y-m') . '/' . date('d');
        $fileName = $filePath . '/test_' . date('YmdHis');

        $result = \App\Services\Excel::exportExcel('测试', $data, $cellName, $filePath, $fileName, false);
        //$result = \App\Services\Excel::export('测试', $model, $where, $cellName, $filePath, $fileName);
        $data = [
            'filename' => $fileName,
            'url' => $result
        ];

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
    }
}
